package com.jrwd.recycletest;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.alibaba.fastjson.JSON;
import com.jrwd.okhttputils.OkHttpUtils;
import com.jrwd.okhttputils.callback.StringCallback;
import com.jrwd.okhttputils.request.BaseRequest;
import com.jrwd.recycletest.base.ViewHolder;
import com.jrwd.recycletest.mange.Constant;
import com.jrwd.recycletest.state.LoadViewHelper;
import com.jrwd.recycletest.util.AesCrypt;
import com.jrwd.recycletest.util.DensityUtils;
import com.jrwd.recycletest.util.LocationUtil;
import com.jrwd.recycletest.util.QTLog;
import com.jrwd.recycletest.util.SpUtils;
import com.umeng.socialize.UMShareAPI;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends BaseActivity {

    @BindView(R.id.loaded)
    Button loade;
    @BindView(R.id.maptext)
    TextView maptext;
    @BindView(R.id.phone)
    Button phone;
    @BindView(R.id.add)
    Button add;
    private RecyclerView recyclerView;
    private CommonAdapter commonAdapter;
    private List<produck> productList = new ArrayList<produck>();
    ;
    private produck produck;

    private LoadViewHelper loadViewHelper;

    List<String> data = new ArrayList<>();

    private Button share;

    private String mShareRegisterUrl = "https://www.baidu.com/";


    List<String> list = new ArrayList<String>();
    private EntranceAdapter mEntranceAdapter;
    private ViewPager mEntranceViewPager;
    private IndicatorView mEntranceIndicatorView;
    private int spancount = 2;

    private Button webview2;
    private LinearLayout llHome;
    private LocationUtil location;
    private PopupWindow mPopupWindow;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);


        ButterKnife.bind(this);
        initdata();


        location = new LocationUtil(this);

        recycle();
        viewpaper();
        mytext();
        web();
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.REQUEST_INSTALL_PACKAGES, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
                ActivityCompat.requestPermissions(this, mPermissionList, 123);

            }

        }
        pullProList();
        share = findViewById(R.id.share);
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    //判断该应用是否有写SD卡权限，如果没有再去申请
                    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 123);

                    } else {
                        new ShareUtils(MainActivity.this)
                                .shareUrl(mShareRegisterUrl);
                    }
                } else {
                    //判断该应用是否有写SD卡权限，如果没有再去申请
                    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 123);
                    } else {
                        new ShareUtils(MainActivity.this).shareUrl(mShareRegisterUrl);
                    }
                }
            }
        });
        llHome = findViewById(R.id.llHome);
        initLoadingHelper(llHome);
        showLoadingView();

    }


    public void showLoadingView() {

        if (loadViewHelper == null) {
            return;
        }
        loadViewHelper.showLoading(R.layout.layout_load_ing);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @OnClick({R.id.loaded, R.id.phone,R.id.add})
    public void onclick(Button button) {
        switch (button.getId()) {
            case R.id.loaded:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 124);
                        location.startLocation();
                    } else {
                        location.startLocation();
                        String s = (String) SpUtils.get(this, "city", "");
                        String a = (String) SpUtils.get(this, "province", "");

                        if (!s.isEmpty())
                            maptext.setText("你现在位于" + a + "" + s);
                    }

                } else {
                    location.startLocation();
                    String s = (String) SpUtils.get(this, "city", "");
                    String a = (String) SpUtils.get(this, "province", "");

                    maptext.setText("你现在位于" + a + "" + s);
                }
                break;
            case R.id.phone:
                if (Build.VERSION.SDK_INT >= 23) {


//                        Toast.makeText(MainActivity.this, "请授权！", Toast.LENGTH_LONG).show();
//
//                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
//                        Uri uri = Uri.fromParts("package",getPackageName(), null);
//                        intent.setData(uri);
//                        startActivity(intent);
//                        Intent intent1 = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
//                        startActivity(intent1);
                    showPopupWindow();
                    Intent intent2 = new Intent(Intent.ACTION_CALL);
                    Uri data = Uri.parse("tel:" + "18378337835");
                    intent2.setData(data);
                    startActivity(intent2);


                } else {
                    showPopupWindow();
                    Intent intent = new Intent(Intent.ACTION_CALL);
                    Uri data = Uri.parse("tel:" + "18378337835");
                    intent.setData(data);
                    startActivity(intent);

                }

                break;
            case R.id.add:
                Intent intent =new Intent(MainActivity.this,login.class);
                startActivity(intent);
                break;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void showPopupWindow() {
        View contentview = LayoutInflater.from(this).inflate(R.layout.test, null);
        mPopupWindow = new PopupWindow(contentview,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);


        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);

        mPopupWindow.setContentView(contentview);

        mPopupWindow.showAtLocation(contentview, Gravity.CENTER, 0, 0);


    }

    private void web() {
        webview2 = findViewById(R.id.webView2);
        webview2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, WebViewAct.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 123) {

            if (grantResults.length >= 1) {
                //因为我们只申请了一个权限，所以这个数组只有一个
                int writeResult = grantResults[0];
                int writeResult1 = grantResults[2];

                //判断是否授权，也就是用户点击的是拒绝还是接受
                boolean writeGranted = writeResult == PackageManager.PERMISSION_GRANTED;
                boolean writeGranted1 = writeResult1 == PackageManager.PERMISSION_GRANTED;
                if (writeGranted) {

                    //用户点击了接受，可以进行相应处理
//                    new ShareUtils(MainActivity.this)
//                            .shareUrl(mShareRegisterUrl);
                } else {
                    //用户点击了拒绝，可以进行相应处理
                    Toast.makeText(MainActivity.this, "分享需要获取对应的权限，否则无法分享", Toast.LENGTH_SHORT).show();
                }
                if (writeGranted1) {
                    location.startLocation();

                }
            }
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();

        if (location != null) {
            location.destoryLocation();
        }
    }


    private void initdata() {
        for (int i = 1; i <= 9; i++) {
            data.add(i + "个");
        }
    }

    private void mytext() {

        ViewFlipper viewFlipper = findViewById(R.id.filpper);


        for (int i = 0; i < 5; i++) {
            View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.content, null);
            //   view.findViewById(R.id.tess).setTooltipText();
            TextView tess = view.findViewById(R.id.tess);
            tess.setText("第" + i + "条");
            TextView tess2 = view.findViewById(R.id.tess2);
            tess2.setText("第" + i + "肌肤的色卡");
            viewFlipper.addView(view);


        }


    }


    private void viewpaper() {
        mEntranceViewPager = findViewById(R.id.star_viewPager);
        mEntranceIndicatorView = findViewById(R.id.star_indicator);

    }

    private void setStarData(List<HomeRes.DataBean.ProductStarBean> product_star) {
        LayoutInflater inflater = LayoutInflater.from(this);
        //将RecyclerView放至ViewPager中：
        int pageSize = 2;
        //一共的页数等于 总数/每页数量，并取整。
        int pageCount = (int) Math.ceil(product_star.size() * 1.0 / pageSize);//页数
        List<View> viewList = new ArrayList<View>();
        for (int index = 0; index < pageCount; index++) {
            //每个页面都是inflate出一个新实例
            LinearLayout lLayout = (LinearLayout) inflater.inflate(R.layout.item_home_entrance_vp, mEntranceViewPager, false);
            RecyclerView recyclerView = lLayout.findViewById(R.id.view_recyleview);

            recyclerView.setLayoutManager(new GridLayoutManager(this, spancount));

            mEntranceAdapter = new EntranceAdapter(this, this, product_star, index, spancount);
            recyclerView.setAdapter(mEntranceAdapter);
            viewList.add(recyclerView);
        }

        CagegoryViewPagerAdapter adapter = new CagegoryViewPagerAdapter(viewList);
        mEntranceViewPager.setAdapter(adapter);
        mEntranceIndicatorView.setIndicatorCount(mEntranceViewPager.getAdapter().getCount());
        mEntranceIndicatorView.setCurrentIndicator(mEntranceViewPager.getCurrentItem());
        mEntranceViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                mEntranceIndicatorView.setCurrentIndicator(position);
            }
        });

        mEntranceAdapter.notifyDataSetChanged();
    }

    private void pullProList() {

        String json = Constant.paramsBuilder(this)
                .setParams("type", 1)
                .build();
        OkHttpUtils.post(Api.GET_HOME_LIST)
                .params(Constant.SERVER_PARAM, json)
                .tag(1)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean b, String s, Request request, @Nullable Response response) {
                        try {
                            s = new AesCrypt().decrypt(s);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        QTLog.d("yxb----product---" + s);
                        final HomeRes homeRes = JSON.parseObject(s, HomeRes.class);
                        HomeRes.DataBean data = homeRes.getData();
                        if (homeRes != null && homeRes.isSuccess()) {
                            List<HomeRes.DataBean.ProductStarBean> product_star = data.getProduct_star();

                            if (product_star != null && product_star.size() > 0) {
                                setStarData(product_star);
                            }

                            // isVisvible = true;
                            // showSuccessView();

                        } else {
                            //noData();
                        }
                    }

                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
//                        if (!isVisvible) {
//                            showLoadingView();
//                        }
                    }

                    @Override
                    public void onAfter(boolean isFromCache, @Nullable String s, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onAfter(isFromCache, s, call, response, e);
                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);

                    }
                });
    }

    private void recycle() {
        recyclerView = findViewById(R.id.recyclerView);

        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));


        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST,
                DensityUtils.dp2px(this, 1), getResources().getColor(R.color.colorPrimaryDark)));

        commonAdapter = new CommonAdapter<produck>(this, R.layout.item_product, productList) {
            @Override
            protected void convert(ViewHolder holder, produck p, int position) {
                ImageView iv = holder.getView(R.id.testimage);
                TextView textView = holder.getView(R.id.title1);
                TextView textView2 = holder.getView(R.id.text2);

                iv.setImageResource(p.getImg());
                textView.setText(p.getText1());
                textView2.setText(p.getText2());
            }

        };
        //        把适配器添加到RecycleView中
        recyclerView.setAdapter(commonAdapter);

        for (int i = 0; i < 8; i++) {
            produck = new produck(R.mipmap.icon_eleven_bg, "dda", "dsaf");
            productList.add(produck);
        }
        commonAdapter.notifyDataSetChanged();
    }


}




